//
//  WXSegment.m
//  WXMovie
//
//  Created by 朱思明 on 13-9-9.
//  Copyright (c) 2013年 朱思明. All rights reserved.
//

#import "WXSegment.h"

@implementation WXSegment

- (id)initWithFrame:(CGRect)frame items:(NSArray *)items
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.items = items;
        
        self.selectedIndex = 0;
        _images = [[NSMutableArray alloc]initWithCapacity:self.items.count];
        _labels = [[NSMutableArray alloc]initWithCapacity:self.items.count];
        
        [self _initViews];
    }
    return self;
}

- (void)_initViews
{
    for (int i = 0; i < self.items.count; i++) {
        //创建按钮的背景视图
        UIImage *image = [UIImage imageNamed:@"bp"];
        UIImage *highlightImage = [UIImage imageNamed:@"bp_h"];
        UIImageView *itemBackgroud = [[UIImageView alloc]initWithImage:image highlightedImage:highlightImage];
        //添加到数组中
        [_images addObject:itemBackgroud];
        [self addSubview:itemBackgroud];
        [itemBackgroud release];
        
        //创建按钮标题
        UILabel *itemLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        itemLabel.font = [UIFont systemFontOfSize:14];
        itemLabel.backgroundColor = [UIColor clearColor];
        itemLabel.textAlignment = NSTextAlignmentCenter;
        itemLabel.textColor = [UIColor blackColor];
        //添加到数组中
        [_labels addObject:itemLabel];
        [self addSubview:itemLabel];
        [itemLabel release];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    //每一个按钮的宽度
    float itemWidth = self.width / self.items.count;
    for (int i = 0; i < self.items.count; i++) {
        UIImageView *itemBackground = [_images objectAtIndex:i];
        itemBackground.frame = CGRectMake(i * itemWidth, 0, itemWidth, self.height);
        //设置选中的高亮状态
        if (self.selectedIndex == i) {
            itemBackground.highlighted = YES;
        }
        
        UILabel *itemLabel = [_labels objectAtIndex:i];
        itemLabel.frame = CGRectMake(i * itemWidth, 0, itemWidth, self.height);
        itemLabel.text = [self.items objectAtIndex:i];
    }
}

#pragma mark - touch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    //获取子按钮的宽度
    float itemWidth = self.width / self.items.count;
    //获取子按钮的索引
    int index = point.x / itemWidth;
    if (index < self.items.count) {
        //上次选中图片取消高亮状态
        UIImageView *lastItemBackground = [_images objectAtIndex:self.selectedIndex];
        lastItemBackground.highlighted = NO;
        
        //设置当前选中图片为高亮状态
        UIImageView *itemBackground = [_images objectAtIndex:index];
        itemBackground.highlighted = YES;
        
        self.selectedIndex = index;
        
        //触发一个事件
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}


@end
